package com.superb.common.database.interceptor;

import com.superb.common.database.handler.SuperbParamsEncryptHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

/**
 * 用于处理mapper查询结果字段解密
 *
 * @Author: ajie
 * @CreateTime: 2024-05-11 17:46
 */
@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
@AllArgsConstructor
public class SuperbDecryptInterceptor implements Interceptor {

    /**
     * 加密秘钥
     */
    private final String fieldEncryKey;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement statement = ((MappedStatement) invocation.getArgs()[0]);
        boolean desensitized = !statement.getId().contains("ById");
        // 如果为getById，则无需脱敏
        Object result = invocation.proceed();
        SuperbParamsEncryptHandler.decryptHandler(result, fieldEncryKey, desensitized);
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }



}
